package edu.towson.ait642pareja.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import edu.towson.ait642pareja.client.GreetingService;
import edu.towson.ait642pareja.shared.FieldVerifier;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	static String BREAK = "<br>";

	static String lastWord = new String();
	static int counter = 1;

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid.
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back
			// to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 10 characters long");
		}
		return checkStutter(input);

	}

	public static String checkStutter(String input) {
		/*
		 * Accepts one string array as variable line passed from main method
		 * First step is to split the input into an Array based on Lines then
		 * produce a second array that will be used to compare words in that line. 
		 * If there is a duplicate then print out the two words.
		 */

		counter = 1;
		
		//Array used to split the input into separate lines
		String[] lines = input.split("\n");
		//Array used to split the line into words
		String[] temp;
		String delimiter = "[ .,?!  -+=;:&{}]+";
		
		//Creating and initializing results to send back to greetServer
		String results = "";

		for (int c = 0; c < lines.length; c++) {
			temp = lines[c].split(delimiter);

			for (int i = 0; i < temp.length; i++) {
				if (i + 1 > temp.length - 1) {
					lastWord = temp[i].toString();
					break;
				}

				if (temp[i].equals(temp[i + 1])) {
					results += "Repeated word on line " + counter + ": "
							+ temp[i] + " " + temp[i + 1]
							+ GreetingServiceImpl.BREAK;
				}

				if (temp[i].equals(lastWord)) {
					results += "Repeated word on the line " + (counter - 1)
							+ " and " + counter + ": " + temp[i] + " "
							+ lastWord + GreetingServiceImpl.BREAK;
				}

			}
			counter++;
		}

		return results;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html
	 *            the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
